import { usePermissionStore } from '@/stores/permissionStore';
import { PERMISSIONS, ROLES } from '@/utils/permissions';

// 定义初始状态类型
interface InitialState {
  name?: string;
  currentUser?: {
    id: number;
    username: string;
    email: string;
    is_superuser: boolean;
    is_staff: boolean;
    is_active: boolean;
    [key: string]: any;
  };
}

export default (initialState: InitialState) => {
  // 在这里按照初始化数据定义项目中的权限，统一管理
  // 参考文档 https://umijs.org/docs/max/access

  console.log('access.ts initialState:', initialState);

  // 基础权限检查
  const canSeeAdmin = !!(
    initialState && initialState.currentUser && initialState.currentUser.is_staff
  );

  // 获取权限store的状态（同步）
  const permissionStore = usePermissionStore.getState();

  console.log('access.ts permissionStore:', {
    permissions: permissionStore.permissions,
    roles: permissionStore.roles,
    loading: permissionStore.loading
  });

  // 检查是否为超级用户
  const isSuperUser = initialState?.currentUser?.is_superuser === true;
  console.log('当前用户是否为超级用户:', isSuperUser);

  // 同步权限检查函数
  const checkPermission = (permission: string) => {
    try {
      // 超级用户拥有所有权限
      if (isSuperUser) {
        console.log(`超级用户检查权限 ${permission}: true`);
        return true;
      }

      const hasPermission = permissionStore.hasPermission(permission);
      console.log(`普通用户检查权限 ${permission}: ${hasPermission}`);
      return hasPermission;
    } catch (error) {
      console.error('权限检查失败:', error);
      return false;
    }
  };

  const checkRole = (role: string) => {
    try {
      // 超级用户拥有所有角色
      if (isSuperUser) {
        console.log(`超级用户检查角色 ${role}: true`);
        return true;
      }

      const hasRole = permissionStore.hasRole(role);
      console.log(`普通用户检查角色 ${role}: ${hasRole}`);
      return hasRole;
    } catch (error) {
      console.error('角色检查失败:', error);
      return false;
    }
  };

  // 权限检查结果
  const accessResult = {
    // 基础权限
    canSeeAdmin,

    // 用户管理权限
    canViewUser: checkPermission(PERMISSIONS.USER.VIEW),
    canAddUser: checkPermission(PERMISSIONS.USER.ADD),
    canChangeUser: checkPermission(PERMISSIONS.USER.CHANGE),
    canDeleteUser: checkPermission(PERMISSIONS.USER.DELETE),

    // 权限管理权限
    canViewPermissionCategory: checkPermission(PERMISSIONS.PERMISSION.VIEW_CATEGORY),
    canAddPermissionCategory: checkPermission(PERMISSIONS.PERMISSION.ADD_CATEGORY),
    canChangePermissionCategory: checkPermission(PERMISSIONS.PERMISSION.CHANGE_CATEGORY),
    canDeletePermissionCategory: checkPermission(PERMISSIONS.PERMISSION.DELETE_CATEGORY),

    canViewPermission: checkPermission(PERMISSIONS.PERMISSION.VIEW_PERMISSION),
    canAddPermission: checkPermission(PERMISSIONS.PERMISSION.ADD_PERMISSION),
    canChangePermission: checkPermission(PERMISSIONS.PERMISSION.CHANGE_PERMISSION),
    canDeletePermission: checkPermission(PERMISSIONS.PERMISSION.DELETE_PERMISSION),

    canViewRole: checkPermission(PERMISSIONS.PERMISSION.VIEW_ROLE),
    canAddRole: checkPermission(PERMISSIONS.PERMISSION.ADD_ROLE),
    canChangeRole: checkPermission(PERMISSIONS.PERMISSION.CHANGE_ROLE),
    canDeleteRole: checkPermission(PERMISSIONS.PERMISSION.DELETE_ROLE),

    canViewUserRole: checkPermission(PERMISSIONS.PERMISSION.VIEW_USER_ROLE),
    canAddUserRole: checkPermission(PERMISSIONS.PERMISSION.ADD_USER_ROLE),
    canChangeUserRole: checkPermission(PERMISSIONS.PERMISSION.CHANGE_USER_ROLE),
    canDeleteUserRole: checkPermission(PERMISSIONS.PERMISSION.DELETE_USER_ROLE),

    // 角色权限
    isSuperAdmin: checkRole(ROLES.SUPER_ADMIN),
    isAdmin: checkRole(ROLES.ADMIN),
    isUserManager: checkRole(ROLES.USER_MANAGER),
    isPermissionManager: checkRole(ROLES.PERMISSION_MANAGER),
    isViewer: checkRole(ROLES.VIEWER),

    // 组合权限
    canManageUsers: (() => {
      const canView = checkPermission(PERMISSIONS.USER.VIEW);
      const canAdd = checkPermission(PERMISSIONS.USER.ADD);
      const canChange = checkPermission(PERMISSIONS.USER.CHANGE);
      return canView && (canAdd || canChange);
    })(),

    canManagePermissions: (() => {
      const canViewRole = checkPermission(PERMISSIONS.PERMISSION.VIEW_ROLE);
      const canViewPermission = checkPermission(PERMISSIONS.PERMISSION.VIEW_PERMISSION);
      return canViewRole && canViewPermission;
    })(),

    // AI对话平台权限
    canViewAIProvider: checkPermission(PERMISSIONS.AI_CHAT.VIEW_AI_PROVIDER),
    canAddAIProvider: checkPermission(PERMISSIONS.AI_CHAT.ADD_AI_PROVIDER),
    canChangeAIProvider: checkPermission(PERMISSIONS.AI_CHAT.CHANGE_AI_PROVIDER),
    canDeleteAIProvider: checkPermission(PERMISSIONS.AI_CHAT.DELETE_AI_PROVIDER),

    canViewAIModel: checkPermission(PERMISSIONS.AI_CHAT.VIEW_AI_MODEL),
    canAddAIModel: checkPermission(PERMISSIONS.AI_CHAT.ADD_AI_MODEL),
    canChangeAIModel: checkPermission(PERMISSIONS.AI_CHAT.CHANGE_AI_MODEL),
    canDeleteAIModel: checkPermission(PERMISSIONS.AI_CHAT.DELETE_AI_MODEL),

    canViewAIRole: checkPermission(PERMISSIONS.AI_CHAT.VIEW_AI_ROLE),
    canAddAIRole: checkPermission(PERMISSIONS.AI_CHAT.ADD_AI_ROLE),
    canChangeAIRole: checkPermission(PERMISSIONS.AI_CHAT.CHANGE_AI_ROLE),
    canDeleteAIRole: checkPermission(PERMISSIONS.AI_CHAT.DELETE_AI_ROLE),

    canViewAIConversation: checkPermission(PERMISSIONS.AI_CHAT.VIEW_AI_CONVERSATION),
    canAddAIConversation: checkPermission(PERMISSIONS.AI_CHAT.ADD_AI_CONVERSATION),
    canChangeAIConversation: checkPermission(PERMISSIONS.AI_CHAT.CHANGE_AI_CONVERSATION),
    canDeleteAIConversation: checkPermission(PERMISSIONS.AI_CHAT.DELETE_AI_CONVERSATION),

    canViewMessageTemplate: checkPermission(PERMISSIONS.AI_CHAT.VIEW_MESSAGE_TEMPLATE),
    canAddMessageTemplate: checkPermission(PERMISSIONS.AI_CHAT.ADD_MESSAGE_TEMPLATE),
    canChangeMessageTemplate: checkPermission(PERMISSIONS.AI_CHAT.CHANGE_MESSAGE_TEMPLATE),
    canDeleteMessageTemplate: checkPermission(PERMISSIONS.AI_CHAT.DELETE_MESSAGE_TEMPLATE),

    canViewTokenUsage: checkPermission(PERMISSIONS.AI_CHAT.VIEW_TOKEN_USAGE),

    canViewUserFavorite: checkPermission(PERMISSIONS.AI_CHAT.VIEW_USER_FAVORITE),
    canAddUserFavorite: checkPermission(PERMISSIONS.AI_CHAT.ADD_USER_FAVORITE),
    canChangeUserFavorite: checkPermission(PERMISSIONS.AI_CHAT.CHANGE_USER_FAVORITE),
    canDeleteUserFavorite: checkPermission(PERMISSIONS.AI_CHAT.DELETE_USER_FAVORITE),
  };

  console.log('access.ts 权限检查结果:', accessResult);

  return accessResult;
};
